package Send2ME::Loginza;

use Dancer ':syntax';

prefix '/loginza';

post '/' => sub {
	my $token = params->{'token'};

	my $user = token2User($token);

	if ($user) {
		use Send2ME::Dao::Auth;
		use Send2ME::Dao::User;
		
		my $lUser 	= getUser({ identity => $user->{identity} });
		
		if (!$lUser && createUser($user)) {
			$lUser 	= getUser({ identity => $user->{identity} });
		}
	
		if ($lUser) {
			currentUser($lUser);
			redirect '/';	
			return;
		}		
	} 
	
	template 'login_failed';
};

sub token2User {
	my $token = shift;
	
	#делаем запрос на сервер логинзы
	use HTTP::Request;
	use LWP::UserAgent;

	my $agent = LWP::UserAgent->new;
	my $request =
	  HTTP::Request->new(
		GET => "http://loginza.ru/api/authinfo?token=$token" );
		
	my $response = $agent->request($request);

	if ( $response->is_success ) {
		my $data = from_json $response->decoded_content;
		
		return undef if (!$data->{identity});
		
		my $identity 	= $data->{identity};
		my $name 		= undef;
		
		if ($data->{name} && $data->{name}->{first_name}) {
			$name = $data->{name}->{first_name};
		}
		
		return {
			identity => $identity,
			name => $name
		};
	} 
	
	return undef;
}

1;
